package the.broccoli.weixin.service;

import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.util.SignUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.wisteria.framework.web.BusinessException;
import the.broccoli.weixin.configuration.WistWeiXinProperties;
import the.broccoli.weixin.service.dto.WeiXinCreateRefundDTO;
import the.broccoli.weixin.service.dto.WeiXinCreateRefundResultDTO;
import the.broccoli.weixin.service.dto.WeiXinUnifiedOrderDTO;
import the.broccoli.weixin.service.dto.WeiXinUnifiedOrderResultDTO;
import the.broccoli.weixin.service.support.WeiXinRefundSupport;

import javax.annotation.Resource;

@Slf4j
@Service
public class WeiXinPayService {

    @Resource
    private WistWeiXinProperties wistWeiXinProperties;

    @Resource
    private WxPayService wxPayService;

    @Resource
    private WeiXinRefundSupport weiXinRefundSupport;

    public WeiXinUnifiedOrderResultDTO unifiedOrder(WeiXinUnifiedOrderDTO dto) throws WxPayException {
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        request.setBody(dto.getBody());
        request.setOutTradeNo(dto.getOutTradeNo());
        request.setTotalFee(dto.getTotalFee());
        request.setSpbillCreateIp(dto.getSpbillCreateIp());
        request.setNotifyUrl(dto.getNotifyUrl());
        request.setTradeType(dto.getTradeType());
        request.setOpenid(dto.getOpenId());
        WxPayUnifiedOrderResult wxPayUnifiedOrderResult = this.wxPayService.unifiedOrder(request);
        WeiXinUnifiedOrderResultDTO result = new WeiXinUnifiedOrderResultDTO();
        result.setAppid(wistWeiXinProperties.getMiniappAppid());
        result.setTimeStamp(String.valueOf(System.currentTimeMillis()));
        result.setNonceStr(String.valueOf(System.currentTimeMillis()));
        result.setPrepayId(wxPayUnifiedOrderResult.getPrepayId());
        result.setPaySign(SignUtils.createSign(result.getSignParams(), result.getSignType(), wistWeiXinProperties.getPayMchKey(), null));
        return result;
    }

    public WeiXinCreateRefundResultDTO createRefund(WeiXinCreateRefundDTO dto) {
        WeiXinCreateRefundResultDTO refundResult = null;
        try {
            refundResult = weiXinRefundSupport.createRefund(dto);
        } catch (WxPayException e) {
            log.error("微信退款异常。WeiXinPayService#createRefund。", e);
            throw BusinessException.withMessage("微信退款异常");
        }
        return refundResult;
    }
}
